<!--
 * @Author: life 2145887855@qq.com
 * @Date: 2025-03-23 11:37:11
 * @LastEditors: life 2145887855@qq.com
 * @LastEditTime: 2025-03-29 17:33:01
 * @FilePath: \ruoyi-ui\src\views\system\while\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="会员ID编号" prop="scWhitelistId">
        <el-input
          v-model="queryParams.scWhitelistId"
          placeholder="请输入会员ID编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效开始时间" prop="scValidPeriodStart">
        <el-date-picker
          clearable
          v-model="queryParams.scValidPeriodStart"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择会员车辆特权的有效开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效结束时间" prop="scValidPeriodEnd">
        <el-date-picker
          clearable
          v-model="queryParams.scValidPeriodEnd"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择会员车辆特权的有效结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="scIsActive">
        <el-select placeholder="请选择状态" v-model="queryParams.scIsActive" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            <el-button :type="rule.scIsActive === 1 ? 'danger' : 'success'" size="mini">
              {{ rule }}
            </el-button>
          </ul>
        </template>
      </el-table-column>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:whitelist:add']"
          >新增</el-button
        >
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="whitelistList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员ID" align="center" prop="scWhitelistId" />

      <el-table-column label="会员折扣" align="center" prop="scDiscount" />

      <el-table-column label="免费停车时长" align="center" width="100">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            {{
              rule.scFreeTime
            }}
          </ul>
        </template>
      </el-table-column>

      <el-table-column label="封顶金额" align="center" width="100">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            {{
              rule.scCapAmount
            }}
          </ul>
        </template>
      </el-table-column>

      <el-table-column label="会员基础金额" align="center" width="100">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            {{
              rule.scBaseAmount
            }}
          </ul>
        </template>
      </el-table-column>

      <el-table-column label="基础时间" align="center" width="100">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            {{
              rule.scBaseTime
            }}
          </ul>
        </template>
      </el-table-column>

      <el-table-column
        label="有效开始时间"
        align="center"
        prop="scValidPeriodStart"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scValidPeriodStart, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="有效结束时间"
        align="center"
        prop="scValidPeriodEnd"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scValidPeriodEnd, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <ul v-for="(rule, index) in scope.row.smartChargingRules" :key="index">
            <el-button
              :type="rule.scIsActive === 1 ? 'danger' : 'success'"
              size="mini"
              @click="handleStatusChange(scope.row, rule, index)"
            >
              {{ rule.scIsActive === 1 ? "停用" : "正常" }}
            </el-button>
          </ul>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:whitelist:edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员车辆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 新增绑定ID -->
        <el-form-item label="会员ID编号" prop="scWhitelistId">
          <el-input
            v-model="form.scWhitelistId"
            placeholder="请输入绑定ID"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="会员车辆特权的有效开始时间" prop="scValidPeriodStart">
          <el-date-picker
            clearable
            v-model="form.scValidPeriodStart"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择会员车辆特权的有效开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员车辆特权的有效结束时间" prop="scValidPeriodEnd">
          <el-date-picker
            clearable
            v-model="form.scValidPeriodEnd"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择会员车辆特权的有效结束时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="会员折扣" prop="scDiscount">
          <el-input v-model="form.scDiscount" placeholder="请输入会员折扣" />
        </el-form-item>

        <!-- 新增封顶金额 -->
        <el-form-item label="封顶金额" prop="scCapAmount">
          <el-input v-model="form.scCapAmount" placeholder="请输入封顶金额" />
        </el-form-item>
        <!-- 新增基础金额 -->
        <el-form-item label="基础金额" prop="scBaseAmount">
          <el-input v-model="form.scBaseAmount" placeholder="请输入基础金额" />
        </el-form-item>
        <!-- 新增基础时间 -->
        <el-form-item label="基础时间" prop="scBaseTime">
          <el-input v-model="form.scBaseTime" placeholder="请输入基础时间" />
        </el-form-item>
        <!-- 新增免费停车时长 -->
        <el-form-item label="免费停车时长" prop="scFreeTime">
          <el-input v-model="form.scFreeTime" placeholder="请输入免费停车时长" />
        </el-form-item>
        <!-- 新增加价时间 -->
        <el-form-item label="加价时间" prop="scPriceIncreaseTime">
          <el-input v-model="form.scPriceIncreaseTime" placeholder="请输入加价时间" />
        </el-form-item>
        <!-- 新增加价金额 -->
        <el-form-item label="加价金额" prop="scMarkupAmount">
          <el-input v-model="form.scMarkupAmount" placeholder="请输入加价金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateWhilelistCardRule">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWhitelist,
  getWhitelist,
  updateWhitelistMessage,
  delWhitelist,
  addWhitelist,
  updateWhitelist,
} from "@/api/system/whitelist";

export default {
  name: "Whitelist",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员车辆表格数据
      whitelistList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        scWhitelistId: null,
        scValidPeriodStart: null,
        scValidPeriodEnd: null,
        scIsActive: null,
      },
      // 表单参数
      form: {
        scWhitelistId: "",
        scRuleId: "",
        scValidPeriodStart: "",
        scValidPeriodEnd: "",
        scCapAmount: "",
        scDiscount: "",
        scBaseAmount: "",
        scBaseTime: "",
        scFreeTime: "",
      },
      // 表单校验
      rules: {
        scDiscount: [{ required: true, message: "会员折扣不能为空", trigger: "blur" }],
        scWhitelistId: [{ required: true, message: "会员ID", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询会员车辆列表 */
    getList() {
      this.loading = true;
      listWhitelist(
        this.queryParams.scWhitelistId,
        this.queryParams.scValidPeriodStart,
        this.queryParams.scValidPeriodEnd,
        this.queryParams.scIsActive
      ).then((response) => {
        console.log(response.rows);
        this.whitelistList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scWhitelistId: null,
        scCarId: null,
        scOwnerId: null,
        scValidPeriodStart: null,
        scValidPeriodEnd: null,
        scAddTime: null,
        scUpdateTime: null,
        scDeleteTime: null,
        scDiscount: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scWhitelistId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.open = true;
      this.title = "添加会员车辆";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      listWhitelist(row.scWhitelistId).then((response) => {
        console.log(response.rows[0].scWhitelistId);
        this.form = {
          scWhitelistId: response.rows[0].scWhitelistId,
          scDiscount: response.rows[0].scDiscount,
          scValidPeriodStart: response.rows[0].scValidPeriodStart,
          scValidPeriodEnd: response.rows[0].scValidPeriodEnd,
          scCapAmount: response.rows[0].smartChargingRules[0].scCapAmount,
          scBaseAmount: response.rows[0].smartChargingRules[0].scBaseAmount,
          scBaseTime: response.rows[0].smartChargingRules[0].scBaseTime,
          scFreeTime: response.rows[0].smartChargingRules[0].scFreeTime,
          scPriceIncreaseTime: response.rows[0].smartChargingRules[0].scPriceIncreaseTime,
          scMarkupAmount: response.rows[0].smartChargingRules[0].scMarkupAmount,
        };
        this.isEdit = true;
        this.open = true;
        this.title = "修改月卡规则信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.scWhitelistId != null) {
            updateWhitelist(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWhitelist(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交新增会员规则表单 */
    submitAddWhileListCardRule() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            scWhitelistId: this.form.scWhitelistId,
            scRuleId: this.form.scWhitelistId,
            scValidPeriodStart: this.form.scValidPeriodStart,
            scValidPeriodEnd: this.form.scValidPeriodEnd,
            scCapAmount: this.form.scCapAmount,
            scDiscount: this.form.scDiscount,
            scBaseAmount: this.form.scBaseAmount,
            scBaseTime: this.form.scBaseTime,
            scFreeTime: this.form.scFreeTime,
          };

          addWhitelist(data)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("新增会员规则成功");
                this.open = false; // 关闭对话框
                this.getList(); // 刷新列表
              } else {
                this.$message.error("新增会员规则失败：" + response.msg);
              }
            })
            .catch((error) => {
              console.error(error);
              this.$message.error("网络请求失败");
            });
        }
      });
    },
    handleStatusChange(row, rule, index) {
      this.$confirm(
        rule.scIsActive === 1 ? "确定要下架该规则吗？" : "确定要上架该规则吗？",
        "提示",
        { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
      )
        .then(() => {
          const newStatus = rule.scIsActive === 1 ? 0 : 1;
          updateWhitelist(row.scWhitelistId, newStatus)
            .then(() => {
              this.getList();
            })
            .catch((error) => {
              console.error(error);
              this.$message.error("操作失败");
            });
        })
        .catch(() => {
          // 取消操作，不做处理
        });
    },

    submitUpdateWhilelistCardRule() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const updateData = {
            scWhitelistId: this.form.scWhitelistId,
            scValidPeriodStart: this.form.scValidPeriodStart,
            scValidPeriodEnd: this.form.scValidPeriodEnd,
            scCapAmount: this.form.scCapAmount,
            scDiscount: this.form.scDiscount,
            scBaseAmount: this.form.scBaseAmount,
            scBaseTime: this.form.scBaseTime,
            scFreeTime: this.form.scFreeTime,
          };

          updateWhitelistMessage(updateData)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error("修改失败：" + response.msg);
              }
            })
            .catch((error) => {
              console.error(error);
              this.$message.error("网络请求失败");
            });
        }
      });
    },

    // 确定按钮点击事件
    submitAction() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.submitUpdateWhilelistCardRule();
          } else {
            this.submitAddWhileListCardRule();
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const scWhitelistIds = row.scWhitelistId || this.ids;
      this.$modal
        .confirm('是否确认删除会员车辆编号为"' + scWhitelistIds + '"的数据项？')
        .then(function () {
          return delWhitelist(scWhitelistIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/whitelist/export",
        {
          ...this.queryParams,
        },
        `whitelist_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
